import type { RouteRecordRaw } from 'vue-router'
import type { MenuPageVO } from '@/types/sec/menu.d'

import { getDynamicComponent } from '@/utils/componentUtils'

// 根据后端返回的菜单列表，生成前端导航菜单数组RouteRecordRaw[]，是Element Plus导航菜单的数据源
export const buildNavMenuList = (menuList: MenuPageVO[]): Array<RouteRecordRaw> => {
  const result: Array<RouteRecordRaw> = []

  menuList.forEach((menu: MenuPageVO) => {
    let component
    let path
    if (menu.children && menu.children.length > 0) {
      component = {}
      path = '/p/' + menu.id
    } else {
      component = getDynamicComponent(menu.url)
      path = '/' + menu.url
    }

    const route: RouteRecordRaw = {
      path: path,
      name: path,
      component: component,
      children: [],
      meta: {
        title: menu.name,
        icon: menu.icon,
        breadcrumb: []
      }
    }

    // 有子菜单的情况，递归调用
    if (menu.children && menu.children.length > 0) {
      route.children?.push(...buildNavMenuList(menu.children))
    }

    result.push(route)
  })

  return result
}

// 获取扁平化路由，将多级路由转换成一级路由，返回的数组将被添加至dynamicRoute的children中
export const buildDynamicRouteList = (routeList: Array<RouteRecordRaw>, breadcrumb: Array<String>): Array<RouteRecordRaw> => {
	const result: Array<RouteRecordRaw> = []

	routeList.forEach((item: any) => {
		if (item.meta.title) {
			breadcrumb.push(item.meta.title)
		}

		if (item.children && item.children.length > 0) {
			result.push(...buildDynamicRouteList(item.children, breadcrumb))
		} else {
			item.meta.breadcrumb.push(...breadcrumb)
			result.push(item)
		}

		breadcrumb.pop()
	})
	return result
}
